import { computed, onMounted, ref } from 'vue'
import { useConsultStore } from '@/stores'
import type { FirstDep, Form, PartialConsult } from '@/types/consult'
import type {
  UploaderAfterRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { getDepListApi, getConsultOrderPreApi } from '@/services/consult'
import { getPatientDetailApi } from '@/services/user-patient'
import { uploadApi } from '@/services/file'
import { getOrderApi, payOrderApi } from '@/services/order'

import type { ConsultOrderPreData } from '@/types/consult'
import type { UserPatient } from '@/types/user-patient'
import {
  closeToast,
  showConfirmDialog,
  showDialog,
  showFailToast,
  showLoadingToast,
  showToast
} from 'vant'
import router from '@/router'

const consultStore = useConsultStore()

export function setIllnessType(type: 0 | 1) {
  consultStore.setIllnessType(type)
}

export function dep() {
  const depList = ref<FirstDep[]>([])

  const activeDepIndex = ref(0)

  const depChildren = computed(() => {
    return depList.value[activeDepIndex.value]?.child
  })

  async function getDepList() {
    try {
      const { data } = await getDepListApi()
      depList.value = data
    } catch (error) {
      console.log(error)
    }
  }

  onMounted(() => {
    getDepList()
  })

  function onSeleceDep(id: string) {
    consultStore.setDep(id)
  }

  return {
    depList,
    activeDepIndex,
    depChildren,
    getDepList,
    onSeleceDep
  }
}

export function illness(linkCallback: () => void) {
  const illnessTimeOptions = [
    { label: '一周内', value: 1 },
    { label: '一月内', value: 2 },
    { label: '半年内', value: 3 },
    { label: '半年以上', value: 4 }
  ]
  const consultFlagOptions = [
    { label: '就诊过', value: 1 },
    { label: '未就诊', value: 0 }
  ]

  const form = ref<Form>({
    illnessDesc: '',
    illnessTime: undefined,
    consultFlag: undefined,
    pictures: []
  })

  const pictures = ref()

  const onAfterRead: UploaderAfterRead = async (item) => {
    if (Array.isArray(item)) return
    if (!item.file) return
    item.status = 'uploading'
    item.message = '上传中...'
    try {
      const { data } = await uploadApi(item.file)
      item.status = 'done'
      item.message = undefined
      item.url = data.url
      form.value.pictures?.push(data)
    } catch (error) {
      item.status = 'failed'
      item.message = '上传失败'
    }
  }
  const onDeleteImg = (item: UploaderFileListItem) => {
    form.value.pictures = form.value.pictures?.filter(
      (pic) => pic.url !== item.url
    )
  }

  const disabled = computed(() => {
    console.log(!form.value.illnessDesc)

    return (
      !form.value.illnessDesc ||
      form.value.illnessTime === undefined ||
      form.value.consultFlag === undefined
    )
  })

  const next = () => {
    if (disabled.value) return
    consultStore.setIllness(form.value)
    linkCallback()
  }

  const { consult } = consultStore

  onMounted(async () => {
    if (consult.illnessDesc) {
      try {
        await showConfirmDialog({
          title: '温馨提示',
          message: '是否恢复填写的病情数据',
          closeOnPopstate: false
        })
        form.value.illnessDesc = consult.illnessDesc
        form.value.illnessTime = consult.illnessTime
        form.value.consultFlag = consult.consultFlag
        if (consult.pictures && consult.pictures.length) {
          form.value.pictures = consult.pictures
          pictures.value = consult.pictures
        }
      } catch (err) {
        111
      }
    }
  })

  return {
    illnessTimeOptions,
    consultFlagOptions,
    form,
    pictures,
    disabled,
    next,
    onAfterRead,
    onDeleteImg
  }
}

export function pay(callback: () => void) {
  const illnessDesc = consultStore.consult.illnessDesc

  const payInfo = ref<ConsultOrderPreData>()
  const loadData = async () => {
    const res = await getConsultOrderPreApi({
      type: consultStore.consult.type,
      illnessType: consultStore.consult.illnessType
    })
    payInfo.value = res.data
    // 设置默认优惠券
    consultStore.setCoupon(payInfo.value.couponId)
  }

  const patient = ref<UserPatient>()
  const loadPatient = async () => {
    if (!consultStore.consult.patientId) return
    const res = await getPatientDetailApi(consultStore.consult.patientId)
    patient.value = res.data
  }

  const agree = ref(false)
  const showPay = ref(false)
  const loading = ref(false)
  const orderId = ref('')

  const onShowPayAction = async (show: boolean) => {
    if (!agree.value) return showToast('请勾选支付协议')
    loading.value = true
    try {
      const { data } = await getOrderApi(consultStore.consult)
      consultStore.clear()
      orderId.value = data.id
      showPay.value = show
    } catch (error) {
      showFailToast('订单生成失败')
    } finally {
      loading.value = false
    }
  }

  const onClose = () => {
    orderId.value = ''
    router.push('/user/consult')
  }

  const showReset = () => {
    type Key = keyof PartialConsult
    const validKeys: Key[] = [
      'type',
      'illnessType',
      'depId',
      'illnessDesc',
      'illnessTime',
      'consultFlag',
      'patientId'
    ]
    const valid = validKeys.every(
      (key) => consultStore.consult[key] !== undefined
    )
    if (!valid) {
      return showDialog({
        title: '温馨提示',
        message:
          '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！',
        closeOnPopstate: false
      }).then(() => {
        callback()
      })
    }
  }

  onMounted(() => {
    showReset()
    loadData()
    loadPatient()
  })

  return {
    illnessDesc,
    payInfo,
    patient,
    agree,
    showPay,
    loading,
    orderId,
    onShowPayAction,
    onClose
  }
}
